package controller;
import entity.User;
import util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
                .forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        String url="";
        User user = null;
        String sql = "select * from user where id=? and password=?";
        try (Connection conn = DataSourceUtils.getConnection();
             PreparedStatement st = conn.prepareStatement(sql)) {
            st.setString(1, userName);
            st.setString(2, password);
            try (ResultSet rs = st.executeQuery()) {
                boolean a=rs.next();
                if (a)
                {   url="/home";
                    User u = new User(userName,password);
                    req.getSession().setAttribute("user", u);
                }
                else
                { url="/login";
                }
                resp.sendRedirect(req.getContextPath() + url);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}